import sys

import pytest
import os
import allure
from api.user import user
from common.content_type import ContentType
from common.read_data import data
from common.logger import logger
from common.user_agent import useragent
from core.result_base import ResultBase


BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)


def get_data(file_path,yaml_file_name):
    '''
    获取对应测试类的测试数据
    '''
    try:
        data_file_path = os.path.join(BASE_PATH, "data"+os.sep+file_path, yaml_file_name)
        yaml_data = data.load_yaml(data_file_path)
    except Exception as ex:
        pytest.skip(str(ex))
    else:
        return yaml_data

#第一大类，是基础用户登录的测试数据，返回的assess_token供后面所有的接口调用
#获取到基础的用户登录的测试数据
base_file_path = "base"
base_test_data = get_data(base_file_path,"base_data.yml")

#第二大类，是api模块的单接口测试数据，粒度比较细
#1、获取到用户模块的测试数据
user_file_path = "api_test_data" + os.sep + "user"
user_test_data = get_data(user_file_path,"user_test_data.yml")

#2、获取到用户模块的测试数据
# project_file_path = "api_test_data" + os.sep + "project"
# project_test_data = get_data(project_file_path,"project_test_data.yml")



#第三大类，是场景测试的测试数据，主要关注流程上的
#获取到场景测试的测试数据
# scenario_file_path = "scenario_test_data"
# scenario_data = get_data(scenario_file_path,"scenario_test_data.yml")



@allure.step("前置步骤 ==>> 清理数据")
def step_first():
    logger.info("******************************")
    logger.info("前置步骤开始 ==>> 清理数据")


@allure.step("后置步骤 ==>> 清理数据")
def step_last():
    logger.info("后置步骤开始 ==>> 清理数据")


@allure.step("前置步骤 ==>> 管理员用户登录")
def step_login(username, password):
    logger.info("前置步骤 ==>> 管理员 {} 登录，返回信息 为：{}".format(username, password))


@pytest.fixture(scope="session")
def get_access_token():
    result = ResultBase()
    domain = base_test_data["init_admin_user"]["domain"]
    username = base_test_data["init_admin_user"]["username"]
    password = base_test_data["init_admin_user"]["password"]
    _xsrf = base_test_data["init_admin_user"]["_xsrf"]
    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }
    payload = {
        "domain": domain,
        "username": username,
        "password": password,
        "_xsrf": _xsrf
    }

    #调用api层的登录接口
    res = user.login(params=payload, headers=headers)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
        result.access_token = res.json()["result"]["access_token"]
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{}, trcid: {} ".format(res.json()["status"], res.json(), res.json()['trcid'])
    result.payload = res.json()
    result.response = res
    logger.info("用户登录 ==>> 返回结果 ==>> {}".format(result.response.text))

    yield result.access_token

# access_token = get_access_token()